package com.yueya.im.server.actors;

import akka.actor.AbstractActor;
import akka.japi.pf.ReceiveBuilder;
import com.yueya.im.common.model.ActorMsg;
import com.yueya.im.common.model.ActorMsg.ActorCmd;
import com.yueya.im.common.model.NodeMsg;
import com.yueya.im.common.model.RouteNode;
import com.yueya.im.common.util.JsonMapper;

import static com.yueya.im.common.constant.ImInfo.INIT_SIZE;

public class ConsoleActor extends AbstractActor {
    @Override
    public Receive createReceive() {
        return ReceiveBuilder
                .create()
                .match(ActorCmd.class,cmd ->{
                    if(cmd.getCmdType() == ActorMsg.CmdType.CONSOLE){
                        NodeMsg nodeMsg = getNodeMsg();
                        String msg = JsonMapper.toJsonString(nodeMsg);
                        ActorMsg.ImMessage message = ActorMsg.ImMessage.newBuilder()
                                .setContent(msg).build();
                        ActorCmd recieveCmd = ActorCmd.newBuilder()
                                .setCmdType(ActorMsg.CmdType.CONSOLE)
                                .setMessage(message)
                                .build();
                        getSender().tell(recieveCmd,getSelf());
                    }
                })
                .build();
    }

    private NodeMsg getNodeMsg(){
        NodeMsg nodeMsg = new NodeMsg();
        Runtime runtime = Runtime.getRuntime();
        nodeMsg.setJvmMaxMemory(runtime.maxMemory());
        nodeMsg.setJvmFreeMemory(runtime.freeMemory());
        nodeMsg.setCacheRoutes(ImActorSystem.getInstance().getUserRouteMap().size());
        nodeMsg.setUsers(ImActorSystem.getInstance().getCacheMap().size());
        nodeMsg.setDevices(ImActorSystem.getInstance().getCacheMap().values().size());
        long msgNums = ImActorSystem.getInstance().getUserRouteMap().values()
                .stream().mapToLong(RouteNode::getTimes).sum();
        nodeMsg.setSendMsgs(msgNums);
        nodeMsg.setNodeAddress(ImActorSystem.getInstance().getSelfNode());
        nodeMsg.setMaxRoutes(INIT_SIZE);
        return nodeMsg;
    }
}
